
package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.*;
import com.leyou.item.pojo.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class GoodsService {
    
    @Autowired
    private SpecGroupService specGroupService;


    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private SeckillMapper seckillMapper;

    private static final Logger logger = LoggerFactory.getLogger(GoodsService.class);

    public PageResult<SpuBo> querySpuByPageAndSort(String key, Boolean saleable, Integer page, Integer rows) {
        //1 查询Spu
        //分页,最多查询100条

        PageHelper.startPage(page, Math.min(rows, 100));

        //创建查询条件
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();

        //是否过滤上下架
        if (saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }

        //是否模糊查询
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("title", "%" + key + "%");
        }

        Page<Spu> spus = (Page<Spu>) this.spuMapper.selectByExample(example);

        List<SpuBo> collect = spus.getResult().stream().map(spu -> {
            SpuBo spuBo = new SpuBo();
            //属性拷贝
            BeanUtils.copyProperties(spu, spuBo);
            //查询spu的商品分类,要分3级查
            List<String> strings = this.categoryService.queryNamesByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
            spuBo.setCname(StringUtils.join(strings, "/"));
            return spuBo;
        }).collect(Collectors.toList());
        return new PageResult<>(spus.getTotal(), collect);
    }

    @Transactional
    public void save(SpuBo spuBo) {
        //保存spu
        spuBo.setSaleable(true);
        spuBo.setValid(true);
        spuBo.setCreateTime(new Date());
        spuBo.setLastUpdateTime(new Date());
        this.spuMapper.insert(spuBo);

        //保存spu详情
        spuBo.getSpuDetail().setSpuId(spuBo.getId());
        this.spuDetailMapper.insert(spuBo.getSpuDetail());

        saveSkuAndStock(spuBo.getSkus(), spuBo.getId());

        sendMessage(spuBo.getId(),"insert");

    }

    public void saveSkuAndStock(List<Sku> skus, Long spuId) {
        for (Sku sku : skus) {
            //保存sku信息
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(sku.getCreateTime());
            sku.setSpuId(spuId);
            this.skuMapper.insert(sku);
            //保存库存信息
            Stock stock = new Stock();
            Integer stockNumber = sku.getStock();
            stock.setStock(stockNumber);
            stock.setSkuId(sku.getId());
            this.stockMapper.insert(stock);

        }

    }

    public SpuDetail querySpuDetailBySpuId(Long spuId) {
        return this.spuDetailMapper.selectByPrimaryKey(spuId);
    }

    public List<Sku> querySkuListBySpuId(Long spuId) {
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> skus = this.skuMapper.select(sku);
        skus.forEach(s -> {
            Stock stock = this.stockMapper.selectByPrimaryKey(s.getId());
            s.setStock(stock.getStock());
        });
        return skus;
    }

    @Transactional
    public void updateSpu(SpuBo spuBo) {
        List<Sku> skus = this.querySkuListBySpuId(spuBo.getId());
        if (!CollectionUtils.isEmpty(skus)) {
            List<Long> ids = skus.stream().map(s -> s.getId()).collect(Collectors.toList());
            Example example = new Example(Stock.class);
            example.createCriteria().andIn("skuId", ids);
            this.stockMapper.deleteByExample(example);
            Sku sku = new Sku();
            sku.setSpuId(spuBo.getId());
            this.skuMapper.delete(sku);
        }
        saveSkuAndStock(spuBo.getSkus(), spuBo.getId());
        spuBo.setLastUpdateTime(new Date());
        spuBo.setCreateTime(null);
        spuBo.setValid(null);
        spuBo.setValid(null);
        this.spuMapper.updateByPrimaryKeySelective(spuBo);

        this.spuDetailMapper.updateByPrimaryKeySelective(spuBo.getSpuDetail());

        sendMessage(spuBo.getId(),"update");
    }


    public void updateSaleableById(Long id, Boolean saleable) {
        Spu spu = new Spu();
        spu.setId(id);
        spu.setSaleable(saleable);
        this.spuMapper.updateByPrimaryKeySelective(spu);

    }

    @Transactional
    public void deleteGoodById(Long spuid) {
        Sku sku = new Sku();
        sku.setSpuId(spuid);
        List<Sku> skus = this.skuMapper.select(sku);
        skus.forEach(s -> {
            Stock stock = new Stock();
            stock.setSkuId(s.getId());
            this.stockMapper.delete(stock);
        });
        this.skuMapper.delete(sku);
        this.spuDetailMapper.deleteByPrimaryKey(spuid);
        this.spuMapper.deleteByPrimaryKey(spuid);
        sendMessage(spuid,"delete");

    }

    public Spu querySpuById(Long id){
        Spu spu = this.spuMapper.selectByPrimaryKey(id);
        return spu;
    }

    private void sendMessage(Long id,String type){
        try {
            this.amqpTemplate.convertAndSend("item."+type,id);
        }catch (Exception e){
            logger.error("{}商品消息发送异常,商品id{}",type,id,e);
        }
    }

    public Sku querySkuById(Long id) {
        return this.skuMapper.selectByPrimaryKey(id);
    }

    public int reduceStock(Long skuId,Long num){
        Stock stock = this.stockMapper.selectByPrimaryKey(skuId);
        int i = stock.getStock() - Integer.parseInt(num + "");
        if(i>=0){
            stock.setStock(i);
            this.stockMapper.updateByPrimaryKeySelective(stock);
        }
        return i;
    }

    public List<Seckill> querySeckills() {

        List<Seckill> seckillList = seckillMapper.selectAll();

        seckillList.forEach(seckill -> {
            Sku sku = skuMapper.selectByPrimaryKey(seckill.getSkuId());
            seckill.setSku(sku);
        });
        return seckillList;
    }

    public Map<String, Object> queryseckparams(Long skuid) {
        Map<String,Object> map = new HashMap<>();
        //查询sku
        Sku sku = skuMapper.selectByPrimaryKey(skuid);
        //查询秒杀商品
        Seckill record = new Seckill();
        record.setSkuId(skuid);
        Seckill seckill= seckillMapper.selectOne(record);
        seckill.setSku(sku);
        //查询spu
        Spu spu = spuMapper.selectByPrimaryKey(sku.getSpuId());

        //查询spudetail
        SpuDetail spuDetail = spuDetailMapper.selectByPrimaryKey(spu.getId());

        //查询组类参数
        List<SpecGroup> specGroups = specGroupService.querySpecByCid(spu.getCid3());
        //查询特有规格参数
        List<SpecParam> params = specGroupService.querySpecParamBuGid(null, spu.getCid3(), null, false);
        //处理规格参数
        HashMap<Long, Object> paramMap = new HashMap<>();
        params.forEach(p -> {
            paramMap.put(p.getId(), p.getName());
        });

        //封装seckill
        map.put("seckill",seckill);
        //封装spu
        map.put("spu",spu);
        //封装specgroups
        map.put("specGroups",specGroups);
        //params
        map.put("paramMap",paramMap);
        map.put("spuDetail",spuDetail);

        return map;


    }
    /**
     * 根据skuid集合查询sku集合
     * @return
     */
    public List<SkuSon> querySkusBySkuIds(List<Long> ids) {
        List<Sku> skus = this.skuMapper.selectByIdList(ids);
        List<SkuSon> skuSons = new ArrayList<>();
        skus.forEach(sku -> {
            SkuSon skuSon = new SkuSon();
            BeanUtils.copyProperties(sku, skuSon);
            Spu spu = this.spuMapper.selectByPrimaryKey(sku.getSpuId());
            skuSon.setOldPrice(sku.getPrice());
            System.out.println(spu.getSaleable());
            skuSon.setSaleable(spu.getSaleable());
            if(!skuSon.getSaleable()){
                skuSon.setOldPrice(0L);
            }
            skuSons.add(skuSon);
        });
        return skuSons;
    }

    public List<SpuBo> querySpuBosByCidAndNum(Long cid, Integer num) {
        PageHelper.startPage(1,num);
        Example example = new Example(Spu.class);
        if(cid == 83){
            example.createCriteria().andEqualTo("cid3",cid);
        } else {
            example.createCriteria().andEqualTo("cid1",cid);
        }
        List<Spu> spus = spuMapper.selectByExample(example);
        List<SpuBo> spuBos = spus.stream().map(spu -> {
            SpuBo spuBo = new SpuBo();
            BeanUtils.copyProperties(spu, spuBo);
            Sku record = new Sku();
            record.setSpuId(spuBo.getId());
            spuBo.setSkus(skuMapper.select(record));
            return spuBo;
        }).collect(Collectors.toList());
        return spuBos;
    }
    /**
     * 后台查询秒杀商品并分页
     * @param page
     * @param rows
     * @return
     */
    public PageResult<Seckill> querySpuByPage(Integer page, Integer rows) {
        //1 查询Spu
        //分页,最多查询100条

        PageHelper.startPage(page, Math.min(rows, 100));
        Page<Seckill>  seckills = (Page<Seckill>) this.seckillMapper.selectAll();
        for (Seckill seckill : seckills) {
            Sku sku = this.skuMapper.selectByPrimaryKey(seckill.getSkuId());
            seckill.setSku(sku);
        }
        return new PageResult<>(seckills.getTotal(), seckills);

    }
}
